package com.atguigu.gulimall.ware.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.ware.constant.PurchaseConstant;
import com.atguigu.gulimall.ware.dao.PurchaseDao;
import com.atguigu.gulimall.ware.dao.PurchaseDetailDao;
import com.atguigu.gulimall.ware.dao.WareSkuDao;
import com.atguigu.gulimall.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimall.ware.entity.PurchaseEntity;
import com.atguigu.gulimall.ware.entity.WareSkuEntity;
import com.atguigu.gulimall.ware.feign.PurchaseFeign;
import com.atguigu.gulimall.ware.service.PurchaseService;
import com.atguigu.gulimall.ware.vo.PurcahseInfoDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimall.ware.vo.PurchaseMergeVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Resource
    private PurchaseDetailDao purchaseDetailDao;
    @Resource
    private WareSkuDao wareSkuDao;
    @Resource
    private PurchaseFeign purchaseFeign;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void purchaseMerge(PurchaseMergeVo purchaseMergeVo) {

        Long purchaseId = purchaseMergeVo.getPurchaseId();
        if(purchaseId == null) {
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(PurchaseConstant.PurchaseStatus.PURCHSE_STATUS_CREATERD.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        Long latestPurchaseId = purchaseId;
        List<Integer> items = purchaseMergeVo.getItems();
        List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailDao.selectBatchIds(items);
        purchaseDetailEntities.stream().map(entity -> {

            entity.setPurchaseId(latestPurchaseId);
            entity.setStatus(PurchaseConstant.PurchaseItemStatus.PURCHASEITEM_STATUS_DISTRIBUTED.getCode());
            purchaseDetailDao.updateById(entity);
            return entity;
        }).collect(Collectors.toList());
        PurchaseEntity purchaseEntity = this.getById(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    @Override
    public PageUtils unreceive() {
        List<PurchaseEntity> list = this.list();
        List<PurchaseEntity> purchaseEntityList = list.stream().filter(obj -> {
            return obj.getStatus().equals(PurchaseConstant.PurchaseStatus.PURCHSE_STATUS_CREATERD.getCode()) || obj.getStatus().equals(PurchaseConstant.PurchaseStatus.PURCHASE_STATUS_DISTRIBUTED.getCode());

        }).collect(Collectors.toList());

        Map<String, Object> params = new HashMap<>();
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params)
        );

        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(purchaseEntityList);
        return pageUtils;
    }

    @Override
    public void received(List<Integer> list) {
        // 1.修改采购单
        List<PurchaseEntity> purchaseEntities = this.listByIds(list);
        purchaseEntities.forEach(e -> {
            e.setUpdateTime(new Date());
            e.setStatus(PurchaseConstant.PurchaseStatus.PURCHASE_STATUS_RECEIVED.getCode());
            this.updateById(e);

            // 2.修改采购详情
            List<PurchaseDetailEntity> purchaseDetailEntities = purchaseDetailDao.selectList(new QueryWrapper<PurchaseDetailEntity>().eq("purchase_id", e.getId()));
            purchaseDetailEntities.forEach(obj -> {
                obj.setStatus(PurchaseConstant.PurchaseItemStatus.PURCHASEITEM_STATUS_BUYING.getCode());
                purchaseDetailDao.updateById(obj);
            });
        });

    }

    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo purchaseDoneVo) {
        // 采购详情更改
        List<PurcahseInfoDoneVo> items = purchaseDoneVo.getItems();
        Boolean flag = true;
        for (PurcahseInfoDoneVo e : items) {
            if (e.getStatus() == PurchaseConstant.PurchaseItemStatus.PURCHASEITEM_STATUS_FAILED.getCode()) {
                flag = false;
            }
            PurchaseDetailEntity purchaseDetailEntity = purchaseDetailDao.selectById(e.getItemId());
            purchaseDetailEntity.setStatus(e.getStatus());
            purchaseDetailDao.updateById(purchaseDetailEntity);


            if (flag == true) {
                // 商品库存更改
                WareSkuEntity wareSkuEntities = wareSkuDao.selectOne(new QueryWrapper<WareSkuEntity>().eq("ware_id", purchaseDetailEntity.getWareId()).eq("sku_id", purchaseDetailEntity.getSkuId()));
                if (wareSkuEntities==null) {
                    WareSkuEntity wareSkuEntity = new WareSkuEntity();
                    wareSkuEntity.setSkuId(purchaseDetailEntity.getSkuId());
                    wareSkuEntity.setWareId(purchaseDetailEntity.getWareId());
                    wareSkuEntity.setStock(0);
                    wareSkuEntities = wareSkuEntity;
                    wareSkuDao.insert(wareSkuEntity);
                }
                Integer skuNum = purchaseDetailEntity.getSkuNum();
                Integer stock = wareSkuEntities.getStock();
                wareSkuEntities.setStock(skuNum + stock);
                try {
                    R info = purchaseFeign.info(purchaseDetailEntity.getSkuId());
                    if (info.getCode() == 0) {
                        String name = (String) info.get("name");
                        wareSkuEntities.setSkuName(name);
                    }
                }catch (Exception exception) {
                    exception.printStackTrace();
                }
                wareSkuDao.updateById(wareSkuEntities);
            }
        }
        // 采购单更改
        PurchaseEntity byId = this.getById(purchaseDoneVo.getId());
        byId.setStatus(flag?PurchaseConstant.PurchaseStatus.PURCHASE_STATUS_FINISHED.getCode():PurchaseConstant.PurchaseStatus.PURCHASE_STATUS_HASERROR.getCode());
        this.updateById(byId);

    }

}
